#!/usr/bin/env python
import os
import sys 
import subprocess

LIMIT_MSGLEN = 5

COMMIT_MSG_TEMPLATE = ["ADD", "REFINE", "MERGE", "DEL", "DEV", "FIX"]
LOGINTERFACE_KEYWORDS = ["print(", " dump(", "print (", " dump ("]

def is_xlhall_luafile(fpath):
    if fpath.endswith(".lua"):
        if fpath.find("src_xlhall/xl") != -1:
            return True
    return False
    
def chk_loginterface_call(fcode):
    with open(fcode, "r") as fc:
        strlines = fc.readlines()
        for line in strlines:
            for kword in LOGINTERFACE_KEYWORDS:
                if line.find(kword) != -1:
                    return (False, strlines.index(line))
    return (True, None)
    
def raise_error():
    print ("************pre-commit************")
    sys.exit(1)    


def chk_commit_msg():
    if sys.argv[2] != "message":
        print("Must input the commit msg!")
        raise_error()    
        sys.exit()

    cm_msg = sys.argv[1]
    with open(cm_msg, "r") as f:
        cont = f.read()
        if len(cont) <= LIMIT_MSGLEN:
            print ("Commit msg length must be more then %d !!" % LIMIT_MSGLEN)
            raise_error()
        msglist = cont.split(":")
        if not msglist[0] in COMMIT_MSG_TEMPLATE:
            print(COMMIT_MSG_TEMPLATE)
            print("Commit msg must be fmt like--->>>>ADD:xxx FIX:xxx ... go on!")
            raise_error()
        f.close()

def chk_code_loginterface_call():
    cmd_gitchk = "git diff --staged --name-only HEAD"
    proc = subprocess.Popen(cmd_gitchk, shell=True, stdout=subprocess.PIPE)
    with proc.stdout as std_out:
        for fstaged in std_out.readlines():
            fstaged = fstaged.strip()
            if os.path.isfile(fstaged):
                if not is_xlhall_luafile(fstaged):
                    continue
                print ("Chk the lua file belong xlhall ->%s"%fstaged)
                (isok, line) = chk_loginterface_call(fstaged)
                if not (isok):
                    print ("File %s raise an error! Line number->|%d| find the <print> or <dump> invoke. Use xl Logger instead!"%(fstaged, line))
                    sys.exit(1)

if __name__ == "__main__":
    print ("************pre-commit************")
    chk_commit_msg()
    chk_code_loginterface_call()
    print ("************pre-commit************")